﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.IO;
using USB2XXX;
/**
 * 注意：若运行程序提示找不到USB2XXX.dll文件，可以将工程目录下的USB2XXX.dll和libusb-1.0.dll文件拷贝到exe程序输出目录下即可（一般是./bin/Release或者./bin/Debug目录）
 */
namespace USB2XXX_CAN_SchTest
{
    class Program
    {
        static void Main(string[] args)
        {
            USB_DEVICE.DEVICE_INFO DevInfo = new USB_DEVICE.DEVICE_INFO();
            Int32[] DevHandles = new Int32[20];
            Int32 DevHandle = 0;
            Byte CANSendIndex = 0;
            Byte CANReadIndex = 1;
            bool state;
            Int32 DevNum, ret;
            string dllFilePath = "USB2XXX.dll";
            if (!File.Exists(dllFilePath))
            {
                Console.WriteLine("请先将USB2XXX.dll和libusb-1.0.dll文件复制到exe程序文件输出目录下!");
                Console.WriteLine("dll文件在‘usb2can_lin_pwm_example/sdk/libs/windows’目录下！");
                Console.WriteLine("程序是32位的就复制‘x86’目录下文件，程序是64位的就复制‘x86_64’目录下文件！");
                return;
            }
            //扫描查找设备
            DevNum = USB_DEVICE.USB_ScanDevice(DevHandles);
            if (DevNum <= 0)
            {
                Console.WriteLine("No device connected!");
                return;
            }
            else
            {
                Console.WriteLine("Have {0} device connected!", DevNum);
            }
            DevHandle = DevHandles[0];
            //打开设备
            state = USB_DEVICE.USB_OpenDevice(DevHandle);
            if (!state)
            {
                Console.WriteLine("Open device error!");
                return;
            }
            else
            {
                Console.WriteLine("Open device success!");
            }
            //获取固件信息
            StringBuilder FuncStr = new StringBuilder(256);
            state = USB_DEVICE.DEV_GetDeviceInfo(DevHandle, ref DevInfo, FuncStr);
            if (!state)
            {
                Console.WriteLine("Get device infomation error!");
                return;
            }
            else
            {
                Console.WriteLine("Firmware Info:");
                Console.WriteLine("    Name:" + Encoding.Default.GetString(DevInfo.FirmwareName));
                Console.WriteLine("    Build Date:" + Encoding.Default.GetString(DevInfo.BuildDate));
                Console.WriteLine("    Firmware Version:v{0}.{1}.{2}", (DevInfo.FirmwareVersion >> 24) & 0xFF, (DevInfo.FirmwareVersion >> 16) & 0xFF, DevInfo.FirmwareVersion & 0xFFFF);
                Console.WriteLine("    Hardware Version:v{0}.{1}.{2}", (DevInfo.HardwareVersion >> 24) & 0xFF, (DevInfo.HardwareVersion >> 16) & 0xFF, DevInfo.HardwareVersion & 0xFFFF);
                Console.WriteLine("    Functions:" + DevInfo.Functions.ToString("X8"));
                Console.WriteLine("    Functions String:" + FuncStr);
            }
            //初始化配置CAN
            USB2CANFD.CANFD_INIT_CONFIG CANFDConfig = new USB2CANFD.CANFD_INIT_CONFIG();
            //填充初始化参数
            ret = USB2CANFD.CANFD_GetCANSpeedArg(DevHandle, ref CANFDConfig, 500000, 2000000);
            if (ret != USB2CANFD.CANFD_SUCCESS)
            {
                Console.WriteLine("Get CANFD Speed failed!");
                return;
            }
            else
            {
                Console.WriteLine("Get CANFD Speed Success!");
            }
            CANFDConfig.ISOCRCEnable = 1;//使能ISOCRC
            ret = USB2CANFD.CANFD_Init(DevHandle, CANSendIndex, ref CANFDConfig);
            if (ret != USB2CANFD.CANFD_SUCCESS)
            {
                Console.WriteLine("Config CANFD failed!");
                return;
            }
            else
            {
                Console.WriteLine("Config CANFD Success!");
            }
            ret = USB2CANFD.CANFD_Init(DevHandle, CANReadIndex, ref CANFDConfig);
            if (ret != USB2CANFD.CANFD_SUCCESS)
            {
                Console.WriteLine("Config CANFD failed!");
                return;
            }
            else
            {
                Console.WriteLine("Config CANFD Success!");
            }
            //准备CAN调度表数据
            const int AllMsgNum = 5;
            USB2CANFD.CANFD_MSG[] CanMsg = new USB2CANFD.CANFD_MSG[AllMsgNum];
            for (int i = 0; i < AllMsgNum; i++){
                CanMsg[i].Data = new Byte[64];
                CanMsg[i].Flags = 0;//bit[0]-BRS,bit[1]-ESI,bit[2]-FDF,bit[6..5]-Channel,bit[7]-RXD
                CanMsg[i].DLC = 8;
                CanMsg[i].ID = 0x121+(UInt32)i;
                for (int j = 0; j < CanMsg[i].DLC; j++){
                    CanMsg[i].Data[j] = (Byte)j;
                }
                CanMsg[i].Data[0] = (Byte)i;
                CanMsg[i].TimeStamp = 100;//每帧间隔100ms
            }
            //总共1个调度表，表里面包含20帧数据
            byte[] MsgTabNum=new byte[]{AllMsgNum};
            //调度表循环发送数据
            UInt16[] SendTimes = new UInt16[] { 5 };
            ret = USB2CANFD.CANFD_SetSchedule(DevHandle, CANSendIndex, CanMsg, MsgTabNum, SendTimes, 1);//配置调度表，该函数耗时可能会比较长，但是只需要执行一次即可
            if (ret == USB2CANFD.CANFD_SUCCESS)
            {
                Console.WriteLine("Set CAN Schedule Success");
            }
            else
            {
                Console.WriteLine("Set CAN Schedule Error ret = {0}", ret);
                return;
            }
            ret = USB2CANFD.CANFD_StartSchedule(DevHandle, CANSendIndex, 0, 10, 0);//启动第一个调度表,表里面的CAN帧并行发送
            if (ret == USB2CANFD.CANFD_SUCCESS)
            {
                Console.WriteLine("Start CAN Schedule 1 Success");
            }else{
                Console.WriteLine("Start CAN Schedule 1 Error ret = {0}", ret);
                return;
            }
            //读取接收数据缓冲中的数据
            //将缓冲区转换成指针
            USB2CANFD.CANFD_MSG[] CanMsgBuffer = new USB2CANFD.CANFD_MSG[10240];
            for (int i = 0; i < CanMsgBuffer.Length; i++)
            {
                CanMsgBuffer[i] = new USB2CANFD.CANFD_MSG();
                CanMsgBuffer[i].Data = new Byte[64];
            }
            IntPtr pCanGetMsg = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(USB2CANFD.CANFD_MSG)) * CanMsgBuffer.Length);//申请缓冲区
            for (int t = 0; t < 10; t++)
            {
                int GetMsgNum = USB2CANFD.CANFD_GetMsg(DevHandle, CANReadIndex, pCanGetMsg, CanMsgBuffer.Length);
                if (GetMsgNum > 0)
                {
                    for (int i = 0; i < GetMsgNum; i++)
                    {
                        CanMsgBuffer[i] = (USB2CANFD.CANFD_MSG)Marshal.PtrToStructure((IntPtr)(pCanGetMsg + i * Marshal.SizeOf(typeof(USB2CANFD.CANFD_MSG))), typeof(USB2CANFD.CANFD_MSG));
                        Console.WriteLine("CanMsg[{0}].ID = {1}", i, CanMsgBuffer[i].ID & USB2CANFD.CANFD_MSG_FLAG_ID_MASK);
                        Console.WriteLine("CanMsg[{0}].TimeStamp = {1}", i, CanMsgBuffer[i].TimeStamp);
                        Console.Write("CanMsg[{0}].Data = ", i);
                        for (int j = 0; j < CanMsgBuffer[i].DLC; j++)
                        {
                            Console.Write("{0:X2} ", CanMsgBuffer[i].Data[j]);
                        }
                        Console.WriteLine("\n");
                    }
                }
                else if (GetMsgNum < 0)
                {
                    Console.WriteLine("Get CAN data error!");
                }
                System.Threading.Thread.Sleep(100);
            }
            Marshal.FreeHGlobal(pCanGetMsg);//释放缓冲区
            USB2CANFD.CANFD_StopGetMsg(DevHandle, CANReadIndex);
            USB2CANFD.CANFD_StopSchedule(DevHandle, CANSendIndex);
            USB_DEVICE.USB_CloseDevice(DevHandle);
        }
    }
}
